public class AIPlayer implements Player {
    private char symbol;

    public AIPlayer(char symbol) {
        this.symbol = symbol;
    }

    @Override
    public char getSymbol() {
        return symbol;
    }

    @Override
    public Move makeMove(char[][] board) {
        // Step 1: 尝试自己赢
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i][j] == ' ') {
                    board[i][j] = symbol;
                    if (checkWin(board, symbol)) {
                        board[i][j] = ' '; // 撤回
                        return new Move(i, j);
                    }
                    board[i][j] = ' ';
                }
            }
        }

        // step 2：阻止对手获胜
        char opponent = (symbol == 'X') ? 'O' : 'X';
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i][j] == ' ') {
                    board[i][j] = opponent;
                    if (checkWin(board, opponent)) {
                        board[i][j] = ' ';
                        return new Move(i, j);
                    }
                    board[i][j] = ' ';
                }
            }
        }

        // step 3：以上条件都不满足判断最优下棋位置
        int[][] priority = {
            {1, 1}, // center
            {0, 0}, {0, 2}, {2, 0}, {2, 2}, // corners
            {0, 1}, {1, 0}, {1, 2}, {2, 1}  // edges
        };  

        for (int[] pos : priority) {
            if (board[pos[0]][pos[1]] == ' ')
                return new Move(pos[0], pos[1]);
        }
            return null;
    }

    // 强逻辑判断当前棋盘是否能赢
    private boolean checkWin(char[][] board, char sym) {
        for (int i = 0; i < 3; i++) {
            if (board[i][0] == sym && board[i][1] == sym && board[i][2] == sym) return true;
            if (board[0][i] == sym && board[1][i] == sym && board[2][i] == sym) return true;
        }
        return (board[0][0] == sym && board[1][1] == sym && board[2][2] == sym) ||
               (board[0][2] == sym && board[1][1] == sym && board[2][0] == sym);
    }
}
